package com.pat.java.base.xml;

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class TreeModelFromXML extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4744508123402292089L;
	private JTree tree = null;
	private DefaultTreeModel treeModel = null;
	private static String name = null; // 定义Name元素
	private static String age = null; // 定义Age元素
	private static String address = null; // 定义Address元素
	private static String person = null;
	DefaultMutableTreeNode root = null;
	DefaultMutableTreeNode pTreeNode = null;
	DefaultMutableTreeNode nTreeNode = null;
	DefaultMutableTreeNode aTreeNode = null;
	DefaultMutableTreeNode adTreeNode = null;

	public TreeModelFromXML(String title) throws Exception {
		super(title);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 根据解析器工厂来获得具体的加载文档对象
		DocumentBuilder builder = factory.newDocumentBuilder();
		// 加载XML文件 路径不能是中文
		Document doc = builder.parse("files/people.xml");
		
		NodeList n1 = doc.getElementsByTagName("person");
		root = new DefaultMutableTreeNode("People");
		treeModel = new DefaultTreeModel(root);
		tree = new JTree(treeModel);
		
		for (int i = 0; i < n1.getLength(); i++) {
			// 生成一个Element对象来存放具体节点的值
			Element node = (Element) n1.item(i);
			person = node.getNodeName().toString() + i;
			name = node.getElementsByTagName("name").item(0).getFirstChild()
					.getNodeValue();
			age = node.getElementsByTagName("age").item(0).getFirstChild()
					.getNodeValue();
			address = node.getElementsByTagName("address").item(0)
					.getFirstChild().getNodeValue();

			pTreeNode = new DefaultMutableTreeNode(person);
			nTreeNode = new DefaultMutableTreeNode(name);
			aTreeNode = new DefaultMutableTreeNode(age);
			adTreeNode = new DefaultMutableTreeNode(address);
			pTreeNode.add(nTreeNode);
			pTreeNode.add(aTreeNode);
			pTreeNode.add(adTreeNode);
			treeModel.insertNodeInto(pTreeNode, root, i); // 将每个pTreeNode加到根节点root中
		}
		
		Container c = getContentPane();
		c.add(tree, BorderLayout.CENTER);
		
		final JLabel messageLabel = new JLabel("用户还没有选择!");		
		add(messageLabel, BorderLayout.SOUTH);
		
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent t) {
				TreePath tp = t.getNewLeadSelectionPath();
				messageLabel.setText("您选择了:" + tp.getLastPathComponent());
			}
		});
		
		setSize(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}

	public static void main(String args[]) throws Exception {
		JFrame.setDefaultLookAndFeelDecorated(true);
		new TreeModelFromXML("JTree-XML-Test");
	}
}